import { ref } from "vue";
import openDialog from "@/components/Basic/Dialog";

export function useTodo(todoFormComponent) {
  const todoList = ref([
    {
      title: "示例待办事项",
      level: 1, // 优先级
      createDate: new Date(), // 创建日期
      completionTime: "2025-05-31", // 预计完成时间
      isCompleted: false, // 是否完成
      remark: "备注",
    },
  ]);
  // 添加
  function handleAddTodo() {
    const todoForm = ref({
      title: "",
      level: 1,
      createDate: new Date().toLocaleDateString(),
      completionTime: "", // 预计完成时间
      remark: "", // 备注
    });
    const { close } = openDialog(
      {
        title: `添加待办事项`,
        onConfirm: () => {
          const data = {
            ...todoForm.value,
            isCompleted: false, // 是否完成
            completionDate: "", // 完成时间
            id: Date.now(), // 使用时间戳作为唯一ID
          };
          if (todoForm.value.level === 0) {
            todoList.value.unshift(data);
          } else {
            todoList.value.push(data);
          }
          close();
        },
      },
      todoFormComponent(todoForm)
    );
  }
  // 删除
  function handleDeleteTodo(index) {
    todoList.value.splice(index, 1);
  }
  // 编辑
  function handleEditTodo(index) {
    const todoForm = ref({
      ...todoList.value[index],
    });
    const { close } = openDialog(
      {
        title: `编辑待办事项`,
        onConfirm: () => {
          todoList.value[index] = {
            ...todoForm.value,
          };
          close();
        },
      },
      todoFormComponent(todoForm)
    );
  }
  // 完成
  function handleCompleted(index) {
    todoList.value[index].level = 0;
    todoList.value[index].isCompleted = !todoList.value[index].isCompleted;
    todoList.value[index].completionTime = new Date().toLocaleDateString();
  }

  return {
    todoList,
    handleAddTodo,
    handleDeleteTodo,
    handleEditTodo,
    handleCompleted,
  };
}
